package com.taotao.sso.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.TaotaoResult;
import com.taotao.sso.service.UserLoginService;
import com.taotao.utils.CookieUtils;

/**
 * 用户登录的web层controller
 * @author created by wq
 * @date   Sep 6, 2017---9:16:01 AM
 * @return
 * @throws Exception<br/>
 *==========History========== <br/>
 * taotao-sso-web Sep 6, 2017
 */
@Controller
public class UserLoginController {

	@Autowired
	private UserLoginService loginService;
	
	@Value("${TT_TOKEN}")
	private String TT_TOKEN;
	
	/**
	 * 1.2 用户登录功能：
	 * @param username
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/user/login")
	@ResponseBody
	public TaotaoResult userLogin(String username,String password,
			HttpServletRequest request,HttpServletResponse response){
		//调用业务层
		TaotaoResult result = loginService.userLogin(username, password);
		//将token加入到cookie中【这里使用cookieUtiles中带四个参数的setCookie方法】
		/**
		 * 先通过result中获得token，因为在service层已经将token存入到TaoTaoResult中的data中，方便返回结果到手机端，
		 *  同时该系统也可以适用于B/S结构。所以我们需要在web层先将token取出来
		 */
		String token = result.getData().toString();
		CookieUtils.setCookie(request, response, TT_TOKEN, token);
		return result;
	}
	
	
	@RequestMapping(value="/user/token/{token}")
	@ResponseBody
	public TaotaoResult getUserInfoByToken(@PathVariable String token){
		//1.调用业务层
		TaotaoResult result = loginService.getUserInfoByToken(token);
		//2.判断是否有回调url，如果有，需要使用jsonp来进行跨域操作
		//3.返回结果
		return result;
	}
}
